package my.engine.core;

import my.engine.objects.UrlMapping;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import java.util.logging.Level;

/**
 * Created by IntelliJ IDEA.
 * User: emikolenko
 * Date: 22.02.2008
 * Time: 14:55:07
 */
public class CoreUtils {

    public static void parseMappings(Map<String, UrlMapping> mappings) throws Exception {

        SAXBuilder parser = new SAXBuilder();
        Document doc = parser.build(CoreUtils.class.getResourceAsStream("/my/engine/resources/request-mapping.xml"));

        XPath xpath = XPath.newInstance("/request/mapping");
        List<Element> maps = xpath.selectNodes(doc);

        for (Element el : maps) {
            UrlMapping mapping = new UrlMapping();
            String url = el.getChildText("url");
            String header = el.getChildText("header");
            String menu = el.getChildText("menu");
            String view = el.getChildText("view");
            String footer = el.getChildText("footer");
            String template = el.getChildText("template");
            mapping.setUrl(url);
            mapping.setHeader(header);
            mapping.setMenu(menu);
            mapping.setView(view);
            mapping.setFooter(footer);
            mapping.setTemplate(template);

            List<Element> handlers = el.getChildren("path-handler");
            for (Element handlerElem : handlers) {
                String className = handlerElem.getText();
                mapping.getHandlersClasses().add(className);
                AbstractPathHandler handler = instantiateHandler(className);
                mapping.getHandlers().add(handler);
            }
            mappings.put(url, mapping);
        }

        XPath xpathDef = XPath.newInstance("/request/default");
        List<Element> urls = xpathDef.selectNodes(doc);
        for (Element el : urls) {
            String url = el.getChildText("url");
            FlowManager.defaultUrl = url;
            FlowManager.defUkUrl = "public/uk/" + url;
            FlowManager.defRuUrl = "public/ru/" + url;
            FlowManager.defEnUrl = "public/en/" + url;
        }
    }

    public static AbstractPathHandler instantiateHandler(String className) {
        AbstractPathHandler cl = null;
        try {
            cl = (AbstractPathHandler) Class.forName(className).newInstance();
        } catch (ClassNotFoundException e) {
            Logger.getLogger(CoreUtils.class.getName()).log(Level.SEVERE, null, e);
        } catch (InstantiationException e) {
            Logger.getLogger(CoreUtils.class.getName()).log(Level.SEVERE, null, e);
        } catch (IllegalAccessException e) {
            Logger.getLogger(CoreUtils.class.getName()).log(Level.SEVERE, null, e);
        }
        return cl;
    }
}
